const Router = require('@koa/router');
const { Comment, User, Jingdian, Article } = require('../databases');

const commentRouter = new Router({
    prefix: '/comment'
});

// 获取评论首页
commentRouter.get('/', (ctx, next) => {
    ctx.body = {
        code: 200,
        message: '评论首页',
        data: 'Welcome to comment API',
    };
});

// 创建评论
commentRouter.post('/create', async (ctx, next) => {
    try {
        const { uid, jid, aid, content, parentId } = ctx.request.body;
        
        // 验证用户是否存在
        const user = await User.findByPk(uid);
        if (!user) {
            ctx.body = {
                code: 404,
                message: '用户不存在',
                data: null
            };
            return;
        }

        // 验证至少有一个关联对象（景点或文章）
        if (!jid && !aid) {
            ctx.body = {
                code: 400,
                message: '评论必须关联景点或文章',
                data: null
            };
            return;
        }

        // 验证景点是否存在（如果提供了jid）
        if (jid) {
            const jingdian = await Jingdian.findByPk(jid);
            if (!jingdian) {
                ctx.body = {
                    code: 404,
                    message: '景点不存在',
                    data: null
                };
                return;
            }
        }

        // 验证文章是否存在（如果提供了aid）
        if (aid) {
            const article = await Article.findByPk(aid);
            if (!article) {
                ctx.body = {
                    code: 404,
                    message: '文章不存在',
                    data: null
                };
                return;
            }
        }

        // 验证父评论是否存在（如果提供了parentId）
        if (parentId) {
            const parentComment = await Comment.findByPk(parentId);
            if (!parentComment) {
                ctx.body = {
                    code: 404,
                    message: '父评论不存在',
                    data: null
                };
                return;
            }
        }

        const comment = await Comment.create({
            uid,
            jid,
            aid,
            content,
            parentId
        });

        ctx.body = {
            code: 200,
            message: '创建评论成功',
            data: comment,
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '创建评论失败',
            error: error.message
        };
    }
});

// 获取所有评论列表
commentRouter.get('/list', async (ctx, next) => {
    try {
        const { page = 1, limit = 20, jid, aid } = ctx.query;
        const offset = (page - 1) * limit;
        
        let whereCondition = { status: 'active' };
        if (jid) whereCondition.jid = jid;
        if (aid) whereCondition.aid = aid;

        const { count, rows: comments } = await Comment.findAndCountAll({
            where: whereCondition,
            include: [
                {
                    model: User,
                    as: 'user',
                    attributes: ['uid', 'username']
                },
                {
                    model: Jingdian,
                    as: 'jingdian',
                    attributes: ['jid', 'name'],
                    required: false
                },
                {
                    model: Article,
                    as: 'article',
                    attributes: ['aid', 'title'],
                    required: false
                }
            ],
            order: [['createAt', 'DESC']],
            limit: parseInt(limit),
            offset: parseInt(offset)
        });
        
        ctx.body = {
            code: 200,
            message: '获取评论列表成功',
            data: {
                comments,
                total: count,
                page: parseInt(page),
                limit: parseInt(limit),
                totalPages: Math.ceil(count / limit)
            },
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '获取评论列表失败',
            error: error.message
        };
    }
});

// 根据ID获取评论详情
commentRouter.get('/:id', async (ctx, next) => {
    try {
        const { id } = ctx.params;
        const comment = await Comment.findByPk(id, {
            include: [
                {
                    model: User,
                    as: 'user',
                    attributes: ['uid', 'username']
                },
                {
                    model: Jingdian,
                    as: 'jingdian',
                    attributes: ['jid', 'name'],
                    required: false
                },
                {
                    model: Article,
                    as: 'article',
                    attributes: ['aid', 'title'],
                    required: false
                }
            ]
        });

        if (!comment) {
            ctx.body = {
                code: 404,
                message: '评论不存在',
                data: null
            };
            return;
        }

        ctx.body = {
            code: 200,
            message: '获取评论详情成功',
            data: comment,
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '获取评论详情失败',
            error: error.message
        };
    }
});

// 更新评论
commentRouter.put('/:id', async (ctx, next) => {
    try {
        const { id } = ctx.params;
        const { content } = ctx.request.body;

        const comment = await Comment.findByPk(id);
        if (!comment) {
            ctx.body = {
                code: 404,
                message: '评论不存在',
                data: null
            };
            return;
        }

        await comment.update({
            content: content || comment.content,
            updateAt: new Date()
        });

        ctx.body = {
            code: 200,
            message: '更新评论成功',
            data: comment,
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '更新评论失败',
            error: error.message
        };
    }
});

// 删除评论（软删除）
commentRouter.delete('/:id', async (ctx, next) => {
    try {
        const { id } = ctx.params;
        
        const comment = await Comment.findByPk(id);
        if (!comment) {
            ctx.body = {
                code: 404,
                message: '评论不存在',
                data: null
            };
            return;
        }

        // 软删除，将状态设为deleted
        await comment.update({
            status: 'deleted',
            updateAt: new Date()
        });

        ctx.body = {
            code: 200,
            message: '删除评论成功',
            data: null,
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '删除评论失败',
            error: error.message
        };
    }
});

// 根据用户ID获取评论列表
commentRouter.get('/user/:userId', async (ctx, next) => {
    try {
        const { userId } = ctx.params;
        const { page = 1, limit = 20 } = ctx.query;
        const offset = (page - 1) * limit;
        
        const user = await User.findByPk(userId);
        if (!user) {
            ctx.body = {
                code: 404,
                message: '用户不存在',
                data: null
            };
            return;
        }

        const { count, rows: comments } = await Comment.findAndCountAll({
            where: { uid: userId, status: 'active' },
            include: [
                {
                    model: Jingdian,
                    as: 'jingdian',
                    attributes: ['jid', 'name'],
                    required: false
                },
                {
                    model: Article,
                    as: 'article',
                    attributes: ['aid', 'title'],
                    required: false
                }
            ],
            order: [['createAt', 'DESC']],
            limit: parseInt(limit),
            offset: parseInt(offset)
        });

        ctx.body = {
            code: 200,
            message: '获取用户评论列表成功',
            data: {
                comments,
                total: count,
                page: parseInt(page),
                limit: parseInt(limit),
                totalPages: Math.ceil(count / limit)
            },
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '获取用户评论列表失败',
            error: error.message
        };
    }
});

// 根据景点ID获取评论列表
commentRouter.get('/jingdian/:jid', async (ctx, next) => {
    try {
        const { jid } = ctx.params;
        const { page = 1, limit = 20 } = ctx.query;
        const offset = (page - 1) * limit;
        
        const jingdian = await Jingdian.findByPk(jid);
        if (!jingdian) {
            ctx.body = {
                code: 404,
                message: '景点不存在',
                data: null
            };
            return;
        }

        const { count, rows: comments } = await Comment.findAndCountAll({
            where: { jid, status: 'active' },
            include: [
                {
                    model: User,
                    as: 'user',
                    attributes: ['uid', 'username']
                }
            ],
            order: [['createAt', 'DESC']],
            limit: parseInt(limit),
            offset: parseInt(offset)
        });

        ctx.body = {
            code: 200,
            message: '获取景点评论列表成功',
            data: {
                comments,
                total: count,
                page: parseInt(page),
                limit: parseInt(limit),
                totalPages: Math.ceil(count / limit)
            },
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '获取景点评论列表失败',
            error: error.message
        };
    }
});

// 根据文章ID获取评论列表
commentRouter.get('/article/:aid', async (ctx, next) => {
    try {
        const { aid } = ctx.params;
        const { page = 1, limit = 20 } = ctx.query;
        const offset = (page - 1) * limit;
        
        const article = await Article.findByPk(aid);
        if (!article) {
            ctx.body = {
                code: 404,
                message: '文章不存在',
                data: null
            };
            return;
        }

        const { count, rows: comments } = await Comment.findAndCountAll({
            where: { aid, status: 'active' },
            include: [
                {
                    model: User,
                    as: 'user',
                    attributes: ['uid', 'username']
                }
            ],
            order: [['createAt', 'DESC']],
            limit: parseInt(limit),
            offset: parseInt(offset)
        });

        ctx.body = {
            code: 200,
            message: '获取文章评论列表成功',
            data: {
                comments,
                total: count,
                page: parseInt(page),
                limit: parseInt(limit),
                totalPages: Math.ceil(count / limit)
            },
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '获取文章评论列表失败',
            error: error.message
        };
    }
});

// 获取评论回复列表
commentRouter.get('/reply/:parentId', async (ctx, next) => {
    try {
        const { parentId } = ctx.params;
        const { page = 1, limit = 10 } = ctx.query;
        const offset = (page - 1) * limit;
        
        const parentComment = await Comment.findByPk(parentId);
        if (!parentComment) {
            ctx.body = {
                code: 404,
                message: '父评论不存在',
                data: null
            };
            return;
        }

        const { count, rows: replies } = await Comment.findAndCountAll({
            where: { parentId, status: 'active' },
            include: [
                {
                    model: User,
                    as: 'user',
                    attributes: ['uid', 'username']
                }
            ],
            order: [['createAt', 'ASC']],
            limit: parseInt(limit),
            offset: parseInt(offset)
        });

        ctx.body = {
            code: 200,
            message: '获取评论回复列表成功',
            data: {
                replies,
                total: count,
                page: parseInt(page),
                limit: parseInt(limit),
                totalPages: Math.ceil(count / limit)
            },
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '获取评论回复列表失败',
            error: error.message
        };
    }
});

// 点赞评论
commentRouter.post('/:id/like', async (ctx, next) => {
    try {
        const { id } = ctx.params;
        
        const comment = await Comment.findByPk(id);
        if (!comment) {
            ctx.body = {
                code: 404,
                message: '评论不存在',
                data: null
            };
            return;
        }

        await comment.increment('likeCount');

        ctx.body = {
            code: 200,
            message: '点赞成功',
            data: { likeCount: comment.likeCount + 1 },
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '点赞失败',
            error: error.message
        };
    }
});

module.exports = commentRouter;
